package com.rs.controller.websocket;

import cn.hutool.json.JSONUtil;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * WS服务类
 *
 * @author zhouwz
 */
@Slf4j
@Component
@EqualsAndHashCode
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {

    /**
     * 连接数
     */
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(1);

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    public static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("websocket 关闭！当前连接 数量为[{}]", ONLINE_COUNT.decrementAndGet());
    }

    @OnError
    public void onError(Throwable error) {
        webSocketSet.remove(this);
        error.printStackTrace();
    }

    /**
     * 群发
     *
     * @param message 发送的消息
     */
    public static synchronized void sendMessage(Object message) {
        webSocketSet.forEach(ws ->
                {
                    try {
                        if (ws != null) {
                            ws.session.getBasicRemote().sendText(JSONUtil.toJsonStr(message));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        );
    }
}